#include "include/JniCallJava.h"
#include "include/Constant.h"

JniCallJava::JniCallJava(JavaVM *javaVm, JNIEnv *jniEnv, jobject jPlayerObj) {
    this->javaVm = javaVm;
    this->jniEnv = jniEnv;
    this->jPlayerObj = jniEnv->NewGlobalRef(jPlayerObj);

    jclass jPlayerClass = jniEnv->GetObjectClass(this->jPlayerObj);
    jErrorMid = jniEnv->GetMethodID(jPlayerClass, "onError", "(ILjava/lang/String;)V");
    jPreparedMid = jniEnv->GetMethodID(jPlayerClass, "onPrepared", "()V");
}

JniCallJava::~JniCallJava() {
    jniEnv->DeleteGlobalRef(this->jPlayerObj);
}

void JniCallJava::callOnPrepared(ThreadMode threadMode) {
    if (threadMode == THREAD_MAIN) {
        jniEnv->CallVoidMethod(jPlayerObj, jPreparedMid);
    } else if (threadMode == THREAD_CHILD) {
        JNIEnv *currentThreadEnv;
        if (javaVm->AttachCurrentThread(&currentThreadEnv, nullptr) != JNI_OK) {
            LOGE("get child thread jniEnv error!");
            return;
        }
        currentThreadEnv->CallVoidMethod(jPlayerObj, jPreparedMid);
        javaVm->DetachCurrentThread();
    }
}

void JniCallJava::callOnError(ThreadMode threadMode, int errorCode, char *errorMsg) {
    jstring jErrorMsg = nullptr;
    if (threadMode == THREAD_MAIN) {
        jErrorMsg = jniEnv->NewStringUTF(errorMsg);
        jniEnv->CallVoidMethod(jPlayerObj, jErrorMid, errorCode, jErrorMsg);
        jniEnv->DeleteLocalRef(jErrorMsg);
    } else if (threadMode == THREAD_CHILD) {
        // 通过 JavaVM 获取当前线程的 JNIEnv
        JNIEnv *currentThreadEnv;
        if (javaVm->AttachCurrentThread(&currentThreadEnv, nullptr) != JNI_OK) {
            LOGE("get child thread jniEnv error!");
            return;
        }

        jErrorMsg = currentThreadEnv->NewStringUTF(errorMsg);
        currentThreadEnv->CallVoidMethod(jPlayerObj, jErrorMid, errorCode, jErrorMsg);
        currentThreadEnv->DeleteLocalRef(jErrorMsg);

        javaVm->DetachCurrentThread();
    }
}